package com.example.fufudamowang.mus;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import data.Music;
import data.MusicList;





public class MainActivity extends AppCompatActivity {

    private ImageButton imb_last;
    private ImageButton imb_begin;
    private ImageButton imb_stop;
    private ImageButton imb_next;
    private ListView list;

    //歌曲列表对象
    private ArrayList<Music>musicArrayList;

    //歌曲序号
    private int number=0;

    //状态
    private  int status;

    //广播接收器
    private StatusChangedReceiver receiver;

    //媒体播放类
    private MediaPlayer player;

    private LinearLayout root_Layout;



    private TextView text_Current;
    private TextView text_Duration;
    private SeekBar seekBar;
    private TextView textView;
    private Handler seekBarHandler;

    //当前歌曲的持续时间和当前位置，作用于进度条
    private int duration;
    private int time;

    //进度条控制常量
    private static final int PROGRESS_INCREASE = 0;
    private static final int PROGRESS_PAUSE = 1;
    private static final int PROGRESS_RESET = 2;
    private Menu menu;

    //播放模式常量
    private  static final int MODE_LIST_SEQUENCE=0;
    private static  final int MODE_SINGLE_CYCLE=1;
    private static final int MODE_LIST_CYCLE=2;
    private int playmode;

    //音量控制
    private TextView tv_vol;
    private SeekBar seekbar_vol;


    @Override
    //对视图赋值
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        player=new MediaPlayer();

        findViews();
        registerListenters();
        initMusicList();
        initListView();
        checkMusicfile();


        //初始化进度条的进度（time）是0
        duration=0;
        time=0;
        // 绑定广播接收器，可以接收广播
        bindStatusChangedReceiver();
        initSeekBarHandler();
        Intent intent=new Intent(this, MusicService.class);
        startService(intent);
        status = MusicService.COMMAND_STOP;
        //默认播放模式—顺序
        playmode=MainActivity.MODE_LIST_SEQUENCE;
    }

    //实现启动服务，检查播放状态
    protected void onResume() {
        super.onResume();
        audio_Control();
        sendBroadcastOnCommand(MusicService.COMMAND_CHECK_IS_PLAYING);
        PropertyBean propetry=new PropertyBean(MainActivity.this);
        String theme=propetry.getTheme();
        setTheme(theme);
    }

    /**绑定广播接收器*/
    private void bindStatusChangedReceiver() {
        receiver = new StatusChangedReceiver();
        IntentFilter filter = new IntentFilter(
                MusicService.BROADCAST_MUSICSERVICE_UPDATE_STATUS);
        registerReceiver(receiver, filter);
    }



    //对应组件
    private void findViews() {
        imb_last=(ImageButton)findViewById(R.id.imageButton_last);
        imb_begin=(ImageButton)findViewById(R.id.imageButton_begin);
        imb_stop=(ImageButton)findViewById(R.id.imageButton_stop);
        imb_next=(ImageButton)findViewById(R.id.imageButton_next);
        list = (ListView) findViewById(R.id.LV);
        textView=(TextView)findViewById(R.id.textView);
        seekBar = (SeekBar) findViewById(R.id.seekBar1);
        text_Current = (TextView) findViewById(R.id.textView1);
        text_Duration = (TextView) findViewById(R.id.textView2);
        root_Layout = (LinearLayout) findViewById(R.id.Layout);
        tv_vol=(TextView)findViewById(R.id.main_tv_volumeText);
        seekbar_vol=(SeekBar)findViewById(R.id.main_sb_volumebar);

    }


    //为显示组件注册监听器
    private void registerListenters() {

        imb_last.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(MusicService.COMMAND_PREVIOUS);


            }
        });


        imb_begin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (player != null && player.isPlaying()) {
//                    pause();
//                    imb_begin.setBackgroundResource(R.drawable.button_begin);
//                } else {
//                    play(number);
//                    imb_begin.setBackgroundResource(R.drawable.button_pause);
//                }

                switch (status) {
                    case MusicService.STATUS_PLAYING:
                        sendBroadcastOnCommand(MusicService.COMMAND_PAUSE);
                        break;
                    case MusicService.STATUS_PAUSED:
                        sendBroadcastOnCommand(MusicService.COMMAND_RESUME);
                        break;
                    case MusicService.COMMAND_STOP:
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        break;
                    default:
                        break;
                }
            }
        });

        imb_stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                sendBroadcastOnCommand(MusicService.COMMAND_STOP);

            }
        });

        imb_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                numbertoNext();
//                play(number);
//                imb_begin.setBackgroundResource(R.drawable.button_pause);
                sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
            }
        });

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                number = position;
                sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
            }
        });
        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                //进度条暂停移动
                seekBarHandler.sendEmptyMessage(PROGRESS_PAUSE);

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(status!=MusicService.STATUS_STOPPED){
                    time =seekBar.getProgress();
                    text_Current.setText(formatTime(time));
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                }
                if(status == MusicService.STATUS_PLAYING){
                    //发送广播给MusicService，执行跳转
                    sendBroadcastOnCommand(MusicService.COMMAND_SEEK_TO);
                    //进度条恢复移动
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE,1000);
                }

            }

        });
    }





    //初始化音乐列表对象
    private void initMusicList() {
        musicArrayList = MusicList.getMusicList();
        //避免重复添加音乐
        if(musicArrayList.isEmpty())
        {
            //使用ContentProvider,对应ContentResolver
            Cursor mMusicCursor = this.getContentResolver().query(
                    MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null, null, null,
                    MediaStore.Audio.AudioColumns.TITLE);
            //标题
            int indexTitle = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.TITLE);
            //艺术家
            int indexArtist = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.ARTIST);
            //总时长
            int indexTotalTime = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DURATION);
            //路径
            int indexPath = mMusicCursor.getColumnIndex(MediaStore.Audio.AudioColumns.DATA);

            /**通过mMusicCursor游标遍历数据库，并将Music类对象加载带ArrayList中*/
            for (mMusicCursor.moveToFirst(); !mMusicCursor.isAfterLast(); mMusicCursor
                    .moveToNext()) {
                String strTitle = mMusicCursor.getString(indexTitle);
                String strArtist = mMusicCursor.getString(indexArtist);
                String strTotoalTime = mMusicCursor.getString(indexTotalTime);
                String strPath = mMusicCursor.getString(indexPath);

                if (strArtist.equals("<unknown>"))//如果艺术家字段为unknown
                    strArtist = "无艺术家";
                Music music = new Music(strTitle, strArtist, strPath, strTotoalTime);
                musicArrayList.add(music);
            }
        }
    }
/**使用SimpleAdapter适配器把数据绑定到视图
    适配器还有BaseAdapter、SimpleAdapter和ArrayAdapter*/
    private void initListView(){
        List<Map<String,String>>list_map=new ArrayList<Map<String, String>>();
        HashMap<String,String>map;
        SimpleAdapter simpleAdapter;
        for(Music music : musicArrayList){
            map=new HashMap<String,String>();
            map.put("musicName",music.getMusicName());
            map.put("musicArtist",music.getMusicArtist());
            list_map.add(map);

        }
        String[] from =new String[]{"musicName","musicArtist"};
        int[] to={R.id.tv_title,R.id.tv_artist};


        simpleAdapter=new SimpleAdapter(this,list_map,R.layout.listview,from,to);
        list.setAdapter(simpleAdapter);
    }

    /**如果列表没有歌曲，则播放按钮不可用，并提醒用户*/
    private void checkMusicfile()
    {
        if (musicArrayList.isEmpty()) {
            imb_next.setEnabled(false);
            imb_begin.setEnabled(false);
            imb_last.setEnabled(false);
            imb_stop.setEnabled(false);
            Toast.makeText(getApplicationContext(), "没有歌曲文件",Toast.LENGTH_SHORT).show();
        } else {
            imb_next.setEnabled(true);
            imb_begin.setEnabled(true);
            imb_last.setEnabled(true);
            imb_stop.setEnabled(true);
        }
    }

    /**主题设置*/
    private void setTheme(String theme) {
        if("青青草原".equals(theme)) {
            root_Layout.setBackgroundResource(R.drawable.prairie);
        }
        else if ("蓝天白云".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.sky);
        }
        else if ("奇峰罗列".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.mount);
        }
        else if ("浩航宇宙".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.universe);
        }
        else if ("五彩缤纷".equals(theme)){
            root_Layout.setBackgroundResource(R.drawable.colorful);
        }

    }

    /**创建菜单*/
    public boolean onCreateOptionsMenu(Menu menu) {
        this.getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    /**处理菜单点击事件*/
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.menu_theme:
                new AlertDialog.Builder(this)
                        .setTitle("请选择主题").
                        setItems(R.array.theme,
                                new android.content.DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        String theme = PropertyBean.THEMES[which];
                                        MainActivity.this.setTheme(theme);
                                        PropertyBean property = new PropertyBean(MainActivity.this);
                                        property.setAndSaveTheme(theme);
                                    }
                                }).show();
                break;
            case R.id.menu_about:
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("GRacePlayer")
                        .setMessage(R.string.about2).show();
                break;
            case R.id.menu_quit:
                //退出程序
                new AlertDialog.Builder(this)
                        .setTitle("提示").
                        setMessage(R.string.quit).setPositiveButton("确定", new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        System.exit(0);
                    }
                }).setNegativeButton("取消", new android.content.DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                    }
                }).show();
                break;
            case R.id.menu_playmode:
                String[] mode = new String[] { "顺序播放", "单曲循环", "列表循环" };
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        MainActivity.this);
                builder.setTitle("播放模式");
                builder.setSingleChoiceItems(mode, playmode,
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                // TODO Auto-generated method stub
                                playmode = arg1;
                            }
                        });
                builder.setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface arg0, int arg1) {
                                // TODO Auto-generated method stub
                                switch (playmode) {
                                    case 0:
                                        playmode = MainActivity.MODE_LIST_SEQUENCE;
                                        Toast.makeText(getApplicationContext(), R.string.sequence, Toast.LENGTH_SHORT).show();
                                        break;
                                    case 1:
                                        playmode = MainActivity.MODE_SINGLE_CYCLE;
                                        Toast.makeText(getApplicationContext(), R.string.singlecycle, Toast.LENGTH_SHORT).show();
                                        break;
                                    case 2:
                                        playmode = MainActivity.MODE_LIST_CYCLE;
                                        Toast.makeText(getApplicationContext(), R.string.listcycle, Toast.LENGTH_SHORT).show();
                                        break;
                                    default:
                                        break;
                                }
                            }
                        });
                builder.create().show();
                break;

        }
        return super.onOptionsItemSelected(item);
    }

    /** 发送命令，控制音乐播放 */
    private void sendBroadcastOnCommand(int command) {

        Intent intent = new Intent(MusicService.BROADCAST_MUSICSERVICE_CONTROL);
        intent.putExtra("command", command);
        /** 根据不同命令，封装不同的数据*/
        switch (command) {
            case MusicService.COMMAND_PLAY:
                intent.putExtra("number", number);
                break;
            case MusicService.COMMAND_SEEK_TO:
                intent.putExtra("time",time);
                break;

            case MusicService.COMMAND_PREVIOUS:
            case MusicService.COMMAND_NEXT:
            case MusicService.COMMAND_PAUSE:
            case MusicService.COMMAND_STOP:
            case MusicService.COMMAND_RESUME:
            default:
                break;
        }
        sendBroadcast(intent);
    }

    private String formatTime(int msec) {
        int minute = msec / 1000 / 60;
        int second = msec / 1000 % 60;
        String minuteString;
        String secondString;
        if (minute < 10) {
            minuteString = "0" + minute;
        } else {
            minuteString = "" + minute;
        }
        if (second < 10) {
            secondString = "0" + second;
        } else {
            secondString = "" + second;
        }
        return minuteString + ":" + secondString;
    }




    /**内部类，用于播放器状态更新*/
    class StatusChangedReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {

            String musicName=intent.getStringExtra("musicName");
            String musicArtist=intent.getStringExtra("musicArtist");

            status = intent.getIntExtra("status", -1);
            switch (status) {
                case MusicService.STATUS_PLAYING:
                    seekBarHandler.removeMessages(PROGRESS_INCREASE);
                    time = intent.getIntExtra("time", 0);
                    duration = intent.getIntExtra("duration", 0);
                    number = intent.getIntExtra("number", number);
                    list.setSelection(number);
                    seekBar.setProgress(time);
                    seekBar.setMax(duration);
                    seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                    text_Duration.setText(formatTime(duration));
                    imb_begin.setBackgroundResource(R.drawable.pause);
                    //设置textview文字，提示已经播放的歌曲
                    MainActivity.this.setTitle("正在播放:" + musicName + " - " + musicArtist);
                    MainActivity.this.textView.setText(musicArtist + " - " + musicName);
                    break;
                case MusicService.STATUS_PAUSED:
                    time = intent.getIntExtra("time", 0);
                    Message msg=seekBarHandler.obtainMessage();
                    msg.arg1=time;
                    msg.what=PROGRESS_PAUSE;
                    msg.sendToTarget();
                    imb_begin.setBackgroundResource(R.drawable.begin);
                    MainActivity.this.textView.setText(musicArtist + " - " + musicName);
                    break;
                case MusicService.STATUS_STOPPED:
                    time = 0;
                    duration = 0;
                    text_Current.setText(formatTime(time));
                    text_Duration.setText(formatTime(duration));
                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("");
                    imb_begin.setBackgroundResource(R.drawable.begin);
                    break;
                case MusicService.STATUS_COMPLETED:
                    number = intent.getIntExtra("number", 0);
                    //顺序播放
                    if (playmode==MainActivity.MODE_LIST_SEQUENCE)
                    {
                        if (number==MusicList.getMusicList().size()-1) {
                            sendBroadcastOnCommand(MusicService.STATUS_STOPPED);
                        }
                        else{
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                        }
                    }
                    //单曲循环
                    else if(playmode==MainActivity.MODE_SINGLE_CYCLE){
                        sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                    }
                    else if(playmode==MainActivity.MODE_LIST_CYCLE)
                    {
                        if(number==MusicList.getMusicList().size()-1)
                        {
                            number=0;
                            sendBroadcastOnCommand(MusicService.COMMAND_PLAY);
                        }
                        else
                            sendBroadcastOnCommand(MusicService.COMMAND_NEXT);
                    }

                    seekBarHandler.sendEmptyMessage(PROGRESS_RESET);
                    MainActivity.this.setTitle("");
                    imb_begin.setBackgroundResource(R.drawable.begin);
                    break;
                default:
                    break;
            }
        }
    }


//    //读取音乐文件
//   private void load(int number){
//       try{
//           player.reset();//release不可以
//           player.setDataSource(musicArrayList.get(number).getMusicPath());//准备音频
//           player.prepare();
//       }catch (Exception e) {
//           e.printStackTrace();
//       }
//
//   }

//
//    //播放
//    private  void play(int number){
//        //停止
//        if(player!=null&&player.isPlaying()){
//            player.stop();
//        }
//        load(number);
//        player.start();
//
//    }
//
//    private  void pause() {
//        if(player.isPlaying())
//            player.pause();
//    }
//
//    private void stop(){
//        player.stop();
//    }
//
//    //暂停之后，恢复播放
//    private void resume(){
//        player.start();
//    }
//
//
//    //从新播放
//    private void replay(){
//        player.start();
//    }
//    private void numbertoLast() {
//        if(number==0){
//            Toast.makeText(MainActivity.this,MainActivity.this.getString(R.string.tip_top),Toast.LENGTH_SHORT).show();
//        }
//        else
//        {
//            number--;
//            play(number);
//        }
//    }
//    private void numbertoNext(){
//        if(number== MusicList.getMusicList().size()-1)
//            Toast.makeText(MainActivity.this,MainActivity.this.getString(R.string.tip_bottom),Toast.LENGTH_SHORT).show();
//        else
//        {
//            number++;
//            play(number);
//        }
//    }
    private void initSeekBarHandler() {
        seekBarHandler = new Handler() {
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {
                    case PROGRESS_INCREASE:
                        if (seekBar.getProgress() < duration) {
                            //进度条前进一秒
                            seekBar.setProgress(1000);
                           // seekBar.incrementProgressBy(1000);
                            //避免重0开始
                            seekBar.incrementProgressBy(time);
                            seekBarHandler.sendEmptyMessageDelayed(PROGRESS_INCREASE, 1000);
                            //修改显示当前进度的文本
                            text_Current.setText(formatTime(time));
                            time += 1000;
                        }
                        break;
                    case PROGRESS_PAUSE:
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(msg.arg1);
                        break;
                    case PROGRESS_RESET:
                        //重置进度条画面
                        seekBarHandler.removeMessages(PROGRESS_INCREASE);
                        seekBar.setProgress(0);
                        text_Current.setText("00:00");
                        break;
                }
            }
        };
    }
    private void audio_Control(){
        //获取音量管理器
        final AudioManager audioManager=(AudioManager)this.getSystemService(Context.AUDIO_SERVICE);

        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        //zhendui媒体音乐调音量
        final  int max_progress=audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
        seekbar_vol.setMax(max_progress);
        //获取当前音量
        int progress=audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekbar_vol.setProgress(progress);
        tv_vol.setText("音量: "+(progress*100/max_progress)+"%");
        seekbar_vol.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onStopTrackingTouch(SeekBar arg0) {
                // TODO Auto-generated method stub
            }
            @Override
            public void onStartTrackingTouch(SeekBar arg0) {
                // TODO Auto-generated method stub
            }
            @Override
            public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {
                // TODO Auto-generated method stub
                tv_vol .setText("音量： "+(arg1*100)/(max_progress)+"%");
                audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, AudioManager.FLAG_PLAY_SOUND);
            }
        });
    }
    //重写onkeyDown函数
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        int progress;
        switch(keyCode)
        {


            case KeyEvent.KEYCODE_VOLUME_DOWN:
                progress = seekbar_vol.getProgress();
                if(progress != 0)
                    seekbar_vol.setProgress(progress-1);
                return true;
            case KeyEvent.KEYCODE_VOLUME_UP:
                progress = seekbar_vol.getProgress();
                if(progress != seekbar_vol.getMax())
                    seekbar_vol.setProgress(progress+1);
                return true;
            default:
                break;
        }
        return false;
    }




}
